package com.codesuc.aichat.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description 自定义线程池配置
 * @Author Mr.Zhang
 * @Date 2025/8/7 12:54
 * @Version 1.0
 */
@Slf4j
@Configuration
public class ThreadPoolConfig {

    /**
     * 核心线程数
     */
    @Value("${thread-pool.core-pool-size}")
    private Integer corePoolSize;

    /**
     * 最大线程数
     */
    @Value("${thread-pool.max-pool-size}")
    private Integer maxPoolSize;

    /**
     * 队列容量
     */
    @Value("${thread-pool.queue-capacity}")
    private Integer queueCapacity;

    /**
     * 线程前缀名
     */
    @Value("${thread-pool.thread-name-prefix}")
    private String namePrefix;

    /**
     * 线程空闲时间
     */
    @Value("${thread-pool.keep-alive-seconds}")
    private Integer keepAliveSeconds;

    /**
     * 自定义虚拟线程
     *
     * @return
     */
    @Bean(name = "virtualThreadPool")
    public Executor virtualThreadPool() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    /**
     * 自定义平台线程池
     * <br>
     * 平台线程即普通的线程，为了区分 JDK 新出来的虚拟线程所取的名字
     *
     * @return
     */
    @Bean(name = "platformThreadPool")
    public Executor customThreadPool() {
        // 获取可用处理器的 Java 虚拟机的数量
        log.info("系统最大线程数 -> {}", Runtime.getRuntime().availableProcessors());

        // 实例化自定义线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 任务队列大小
        executor.setQueueCapacity(queueCapacity);
        // 线程前缀名
        executor.setThreadNamePrefix(namePrefix);
        // 线程的空闲时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程初始化
        executor.initialize();
        log.info("customThreadPool init finish");
        return executor;
    }

}
